<template>
  <div class="box">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <!-- 歌手名 -->
      <el-form-item label="歌手名" prop="singerName">
        <el-input v-model="ruleForm.singerName"></el-input>
      </el-form-item>
      <!-- 艺名 -->
      <el-form-item label="艺名">
        <el-input v-model="ruleForm.stageName"></el-input>
      </el-form-item>
      <!-- 图片 -->
      <el-form-item label="图片">
        <template>
          <el-col :span="12">
            <img :src="url" alt="" v-if="url" />
          </el-col>
          <el-col :span="12">
            <input
              name="file"
              type="file"
              accept="image/png,image/gif,image/jpeg"
              @change="update"
            />
          </el-col>
        </template>
      </el-form-item>
      <!-- 性别 -->
      <el-form-item label="性别">
        <el-col :span="16">
          <el-radio-group v-model="ruleForm.sex1" @change="changeSex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
            <el-radio label="保密"></el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <!-- 歌手生日 -->
      <el-form-item label="歌手生日">
        <el-col :span="16">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="ruleForm.birthday1"
            style="width: 100%"
            @change="changeBirthday"
          ></el-date-picker>
        </el-col>
      </el-form-item>
      <!-- 大学 -->
      <el-form-item label="大学">
        <el-input v-model="ruleForm.university"></el-input>
      </el-form-item>
      <!-- 国籍 -->
      <el-form-item label="国籍">
        <el-input v-model="ruleForm.nationality"></el-input>
      </el-form-item>
      <!-- 地区 -->
      <el-form-item label="地区">
        <el-input v-model="ruleForm.address"></el-input>
      </el-form-item>
      <!-- 简介 -->
      <el-form-item label="简介" prop="singerIntroduction">
        <el-input
          type="textarea"
          v-model="ruleForm.singerIntroduction"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" v-if="alter != 'true'"
          >立即添加</el-button
        >
        <el-button type="primary" @click="alterBtn" v-else>立即修改</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      ruleForm: {
        singerName: "",
        stageName: "",
        singerUrl: "",
        sex1: "保密",
        sex: "0",
        birthday1: "",
        birthday: "",
        university: "",
        nationality: "",
        address: "",
        singerIntroduction: "",
      },
      rules: {
        singerName: [
          { required: true, message: "请输入歌手名", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        singerIntroduction: [
          { required: true, message: "请输入歌手简介", trigger: "blur" },
        ],
      },
      url: "",
      alter: "",
      id: 0,
    };
  },
  methods: {
    // 添加
    onSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios
            .post("api/singer/addSinger", {
              singerName: this.ruleForm.singerName,
              singerUrl: this.ruleForm.singerUrl,
              singerIntroduction: this.ruleForm.singerIntroduction,
              stageName: this.ruleForm.stageName,
              sex: this.ruleForm.sex,
              birthday: this.ruleForm.birthday,
              address: this.ruleForm.address,
              university: this.ruleForm.university,
              nationality: this.ruleForm.nationality,
            })
            .then((res) => {
              if (res.data.msg == "操作成功") {
                alert("添加成功");
                this.$router.push({
                  name: "singerList",
                  params: { breaks: true },
                });
              } else {
                alert("添加失败！");
              }
            });
        } else {
          return false;
        }
      });
    },
    // 修改
    alterBtn() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios
            .post("api/singer/updateSingerById", {
              id: this.id,
              singerName: this.ruleForm.singerName,
              singerUrl: this.ruleForm.singerUrl,
              singerIntroduction: this.ruleForm.singerIntroduction,
              stageName: this.ruleForm.stageName,
              sex: this.ruleForm.sex,
              birthday: this.ruleForm.birthday,
              address: this.ruleForm.address,
              university: this.ruleForm.university,
              nationality: this.ruleForm.nationality,
            })
            .then((res) => {
              if (res.data.msg == "操作成功") {
                alert("修改成功");
                this.$router.push({
                  name: "singerList",
                  params: { breaks: true },
                });
              } else {
                alert("修改失败！");
              }
            });
        } else {
          return false;
        }
      });
    },
    // 取消
    cancel() {
      this.$router.push("/singerList");
    },
    // 获取图片路径
    update(e) {
      let file = e.target.files[0];
      // console.dir(URL.createObjectURL(file));
      this.url = URL.createObjectURL(file);
      let param = new FormData(); // 创建form对象
      param.append("file", file); // 通过append向form对象添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      // 添加请求头
      axios
        .post("http://192.168.0.26:8081/file/uploadFile", param, config)
        .then((res) => {
          this.ruleForm.singerUrl = res.data.data;
        });
    },
    // 修改性别触发
    changeSex() {
      switch (this.ruleForm.sex1) {
        case "保密":
          this.ruleForm.sex = 0;
          break;
        case "男":
          this.ruleForm.sex = 1;
          break;
        case "女":
          this.ruleForm.sex = 2;
          break;

        default:
          break;
      }
    },
    // 修改生日触发
    changeBirthday() {
      // console.dir(this.ruleForm.birthday1.toISOString().slice(0,10));
      var str = this.ruleForm.birthday1.toISOString();
      this.ruleForm.birthday =
        str.slice(0, 9) + String(Number(str.slice(9, 10)) + 1);
      console.dir(this.ruleForm.birthday);
    },
  },
  mounted() {
    this.alter = this.$route.query.alter;
    if (this.alter == "true") {
      var FormData = JSON.parse(sessionStorage.getItem("FormData"));
      for (const key in FormData) {
        this.ruleForm[key] = FormData[key];
      }
      this.ruleForm.singerUrl = FormData.singerUrl.slice(
        24,
        FormData.singerUrl.length
      );
      this.ruleForm.birthday = FormData.birthday.split(" ")[0];
      this.url = FormData.singerUrl;
      this.id = Number(FormData.id);
    }
  },
};
</script>
<style scoped>
.box {
  width: 500px;
  margin: 20px auto 0;
}
img {
  width: 50px;
  height: 50px;
}
</style>